Page({
  data: {
    addresses: []
  },
  onLoad() {
    // 从本地存储获取用户 _id
    const user = wx.getStorageSync('user');
    if (!user || !user._id) {
      wx.showToast({
        title: '未获取到用户ID',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    const _id = user._id;

    // 发送请求到服务器获取地址
    wx.request({
      url: 'http://localhost:3000/login/getaddress',
      method: 'POST',
      data: {
        _id
      },
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({
            addresses: res.data.addresses
          });
        } else {
          wx.showToast({
            title: '用户地址列表为空，请添加地址',
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: (err) => {
        console.error('获取地址失败', err);
        wx.showToast({
          title: '获取地址失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },


  deleteAddress: function (event) {
    const uindex = event.currentTarget.dataset.index;
    // const addressId = this.data.addresses[uindex]._id;
    const user = wx.getStorageSync('user');
    // console.log(index);
    let arr = this.data.addresses.filter((itm, index) => {
      // console.log(index, uindex);
      return index != uindex
    });
    wx.request({
      url: 'http://localhost:3000/login/deladdress',
      method: 'POST',
      data: {
        _id: user._id,
        arr
      },
      success: (res) => {
        if (res.data.code === 200) {

          wx.setStorageSync('userid', res.data.user._id)
          wx.setStorageSync('user', res.data.user)

          this.setData({
            addresses: wx.getStorageSync('user').addresses
          })
          console.log(res);
        } else {
          wx.showToast({
            title: '地址删除失败',
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: (err) => {
        console.error('地址删除失败', err);
        wx.showToast({
          title: '地址删除失败',
          icon: 'none',
          duration: 2000
        });
      }
    })
  },
gotoaddress: function () {
  const isEdit = false;  // 设置为 false，表示这是添加地址的页面
  wx.setStorageSync('isEdit', isEdit);  // 存储到本地缓存

  wx.redirectTo({
    url: '/pages/address/address',  // 跳转到地址选择页面
  });
  console.log("跳转到了address");
},
  updateaddress: function (event) {
    // 获取点击的地址索引
    const uindex = event.currentTarget.dataset.index;
    // 获取对应的地址信息
    const address = this.data.addresses[uindex];
    // 跳转到下一个页面并传递地址信息和索引
    wx.navigateTo({
      url: `/pages/chress/chress?data=${encodeURIComponent(JSON.stringify({
        address,
        uindex,
      }))}`,
    });
    console.log('跳转到修改地址页面，传递的数据：', {
      address,
      uindex
    });
  },
  onShow() {
    this.setData({
      addresses: wx.getStorageSync('user').addresses
    })


  },

});